// 封装一个函数 连接数据库
import mysql from 'mysql2/promise'
import config from '../config/index.js';

// 线程池
const pool = mysql.createPool({
    host: config.database.HOST,
    user: config.database.USERNAME,
    password: config.database.PASSWORD,
    database: config.database.DATABASE,
    port: config.database.PORT
});

export const UserServices = {
    // 查询所有数据
    async query(sql, values) {
        try {
            // 通过线程池连接mysql
            const conn = await pool.getConnection();
            // 对连接执行某些操作
            const [rows, fields] = await conn.query(sql, values)
            // 释放连接
            pool.releaseConnection(conn);
            // 返回结果
            return Promise.resolve(rows);
        } catch (err) {
            return Promise.reject(err);
        }

    }




}

// 登录
export const userLogin = (phone, password) => {
    let _sql = `SELECT * FROM user_info WHERE phone="${phone}" AND password="${password}";`;
    return UserServices.query(_sql)
}

// 查账账号
export const userFind = (phone) => {
    let _sql = `SELECT * FROM user_info WHERE phone="${phone}";`
    return UserServices.query(_sql)
}

// 注册 数据存储
export const userRegister = (phone, type) => {
    let _sql = `INSERT INTO user_info(phone,username,type) VALUES("${phone}","家友","${type}");`
    return UserServices.query(_sql)
}

// 根据分类查找笔记
const findNoteListByType = (type, id) => {
    let _sql = `SELECT * FROM note where note_type="${type}" and userId="${id}";`
    return UserServices.query(_sql)
}

const findNoteDetail = (id) => {
    let _sql = `SELECT * FROM note where id="${id}";`
    return UserServices.query(_sql)
}

const sentNoteDetail = (title, note_content, note_type, head_img, nickname, uId) => {
    let _sql = `INSERT INTO note(title,note_content,note_type,head_img,nickname,userId) VALUES("${title}","${note_content}","${note_type}","${head_img}","${nickname}","${uId}");`
    return UserServices.query(_sql)
}



